"""
    这是用于存储游戏运行主逻辑和游戏资源调用的模块
"""
import sys
import pygame as ga
from setting import Setting
from time import sleep
from ship import Ship
from bullet import Bullet
from alien import Alien
from stats import GameStats
from button import Button

class AlienInvasion:
    """管理游戏行为和资源的类"""
    def __init__(self):
        ga.init()
        #必须输入一个元组
        self.clock=ga.time.Clock()
        self.set=Setting()
        # self.screen = ga.display.set_mode((0,0),ga.FULLSCREEN)
        # self.set.screen_width = self.screen.get_rect().width
        # self.set.screen_height = self.screen.get_rect().height
        
        self.set.screen_width = 1200
        self.set.screen_height = 800
        
        self.screen = ga.display.set_mode((self.set.screen_width,self.set.screen_height))
        # self.screen = ga.display.set_mode((1200,800))
        ga.display.set_caption("Alien Invasion")
        self.stats = GameStats(self)
        
        self.ship = Ship(self)
        self.bullets = ga.sprite.Group()
        self.aliens = ga.sprite.Group()
        self._create_fleet()
        self.game_active = False
        self.play_button = Button(self,"Play")

    def run_game(self):
        """"开始游戏的主函数"""
        while True:
            #在这里设置一下程序对于用户的各种输入的反映
            self._check_events()
            #这里每一次都要从新进行设置一次颜色防止后面改变背景存在影响
            if self.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()
            self._update_screen()
            self.clock.tick(60)

    def _check_keydown_events(self,e):
        """响应按下的按钮"""
        if e.key == ga.K_RIGHT:
            self.ship.moving_right = True
        elif e.key == ga.K_LEFT:
            self.ship.moving_left = True
        elif e.key == ga.K_q:
            sys.exit()
        elif e.key == ga.K_SPACE:
            self._fire_bullet()

    def _check_keyup_events(self,e):
        """响应释放的按钮"""
        if e.key == ga.K_RIGHT:
            self.ship.moving_right = False
        elif e.key == ga.K_LEFT:
            self.ship.moving_left = False

    def _check_events(self):
        for e in ga.event.get():
            if e.type == ga.QUIT:
                sys.exit()
            elif e.type == ga.KEYDOWN:
                #下面设计成这样是因为我们的按下左右两个键是会检测到两个事件
                self._check_keydown_events(e)
            elif e.type == ga.KEYUP:
                self._check_keyup_events(e)
            elif e.type == ga.MOUSEBUTTONDOWN:
                mouse_pos = ga.mouse.get_pos()
                self._check_play_button(mouse_pos)
    
    def _check_play_button(self,mouse_pos):
        """在玩家点击Play的按钮时开始新游戏"""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.game_active:
            ga.mouse.set_visible(False)
            self.stats.reset_stats()
            self.game_active = True

            #清空外星人和子弹
            self.bullets.empty()
            self.aliens.empty()
            self.set.initalize_dynamic_set()
            #创建一个新的外星舰队,并将飞船放在屏幕底部的中央
            self._create_fleet()
            self.ship.center_ship()

    def _update_bullets(self):
        self.bullets.update()
        #负责删除已经消失的子弹
        #不能直接对着原来的子弹组进行修改,防止出现遍历的问题
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)
            #测试打印
            # print(len(self.bullets))
            self._check_bullet_alien_collisions()
      

    def _check_bullet_alien_collisions(self):
        """响应子弹和外星人的"""
        collisions = ga.sprite.groupcollide(self.bullets,self.aliens,True,True)
        if not self.aliens:
            #删除现有的所有子弹,并且创建一个新的外星舰队
            self.bullets.empty()
            self._create_fleet()
            self.set.increase_speed()

    def _check_aliens_bottom(self):
        """检查是否有外星人到达看屏幕下边缘"""
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= self.set.screen_height:
                self._ship_hit()
                break
    
    def _update_aliens(self):
        """更新所有的外星人的位置"""
        self._check_fleet_edges()
        self.aliens.update()
        if ga.sprite.spritecollideany(self.ship,self.aliens):
            # print("Ship hit!!!")
            self._ship_hit()
        self._check_aliens_bottom()


    def _update_screen(self):
        """不断刷新着屏幕"""
        self.screen.fill(self.set.bg_color)
        for b in self.bullets.sprites():
            b.draw_bullet()
        self.ship.blitme()
        self.aliens.draw(self.screen)
        if not self.game_active:
            self.play_button.draw_button()

        ga.display.flip()

    def _fire_bullet(self):
        """创建一个新的子弹,并且加入到bullets的资源当中"""
        if len(self.bullets) < self.set.bullet_num:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)
    
    def _create_fleet(self):
        """创建一个新的外星舰队"""
        alien = Alien(self)
        alien_width,alien_hight = alien.rect.size

        current_x = alien_width
        current_y = alien_hight
        while current_y < (self.set.screen_height - 3* alien_hight):
            while current_x < (self.set.screen_width-2*alien_width):
                self._create_alien(current_x,current_y)
                current_x += 2*alien_width
            current_x = alien_width
            current_y += 2*alien_hight

    def _create_alien(self,x_position,y_position):
        new_alien = Alien(self)
        new_alien.x = x_position
        new_alien.rect.x = x_position
        new_alien.rect.y = y_position
        self.aliens.add(new_alien)

    def _check_fleet_edges(self):
        """发现外星人到达边界后改变方向"""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        """改变外星人移动方向,并且将所有的外星人向下移动"""
        for alien in self.aliens.sprites():
            alien.rect.y += self.set.fleet_drop_speed
        self.set.fleet_direction *= -1

    def _ship_hit(self):
        """响应飞船和外星人的碰撞""" 
        if self.stats.ships_left > 0:
            self.stats.ships_left-= 1
            #负责清空屏幕上的外星人和子弹重新开始
            self.bullets.empty()
            self.aliens.empty()
            # 创建新的舰队和GG爆
            self._create_fleet()
            self.ship.center_ship()
            sleep(1)
        else:
            self.game_active = False
            ga.mouse.set_visible(True)





if __name__ == '__main__':
    #负责运行的时候创建游戏实例并且运行游戏
    ai = AlienInvasion()
    ai.run_game()



